package com.appbee.core.client.json;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;

public class Json
{
	private final JSONValue wrap;

	public Json(JSONValue wrap)
	{
		this.wrap = wrap;
	}

	public static Json parseStrict(String json)
	{
		try
		{
			return new Json(JSONParser.parseStrict(json));
		}
		catch (Exception e)
		{
		}
		return new Json(null);
	}

	public String getString(String name, String defaultValue)
	{
		if (wrap == null)
			return defaultValue;
		JSONObject object = wrap.isObject();
		if (object == null)
			return defaultValue;
		JSONValue jsonValue = object.get(name);
		if (jsonValue == null)
			return defaultValue;
		JSONString jsonString = jsonValue.isString();
		if (jsonString == null)
			return defaultValue;
		return jsonString.stringValue();
	}

	public Long getStringAsLong(String name, Long defaultValue)
	{
		String stringValue = getString(name, null);
		if (stringValue == null)
			return defaultValue;

		try
		{
			return Long.parseLong(stringValue);
		}
		catch (Exception ex)
		{
			return defaultValue;
		}
	}

	public Json get(String name)
	{
		if (wrap == null)
			return new Json(null);

		JSONObject object = wrap.isObject();
		if (object == null)
			return new Json(null);

		return new Json(object.get(name));

	}
}
